package com.frxuexi.base.mvvm

import android.util.Log
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.blankj.utilcode.util.SPUtils
import com.frxuexi.base.net.Res
import com.google.gson.Gson
import kotlinx.coroutines.launch
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody
import java.lang.RuntimeException

open class BaseViewModel : ViewModel() {
    val onFailed by lazy { MutableLiveData<Throwable>() }

    fun <T> httpRequest(
        s: suspend () -> Res<T>,
        success: (T) -> Unit,
        failed: (Throwable) -> Unit = onFailed::postValue,
        code:Int=200
    ) {
        viewModelScope.launch {
            try {
                val res = s.invoke()//调用接口
                /*if (res.status == "C0000") {
                    Log.i("===",res.result.toString())
                    success(res.result)
                } else {
                    failed(RuntimeException(res.message))
                }*/
                if(res.code==200){
                    Log.i("===res",res.data.toString())
                    success(res.data)
                }else {
                    failed(RuntimeException(res.message))
                }
            } catch (e: Exception) {
                failed(e)
            }

        }
    }

    fun <T> roomRequest(s:suspend ()->T,
                        success: (T) -> Unit,
                        failed: (Throwable) -> Unit = onFailed::postValue){
        viewModelScope.launch {
            try {
                val invoke = s.invoke()
                success(invoke)
            }catch (e:Exception){
                failed(e)
            }

        }
    }

    fun mapToBody(map: Map<String,Any>):RequestBody{
        val json = Gson().toJson(map)
        val requestBody = RequestBody.create("application/json".toMediaTypeOrNull(), json)
        return requestBody
    }

}